import java.util.Arrays;

/**
 * This class contains all the questions from the first chapter regarding Matrixes.
 *
 * @author Andrey Borisenko
 * @version 1.0
 */

public class Matrixes {
    public static void main(String[] args) {
        int[][] matrixToTest = {
                {1, 2, 3, 4, 5},
                {2, 3, 4, 5, 1},
                {3, 4, 5, 1, 2},
                {4, 5, 1, 2, 0},
                {5, 1, 3, 1, 2}};
        System.out.println("Let's rotate our matrix on 90 degrees clockwise:");
        System.out.println(Arrays.deepToString(rotateImageMatrix(matrixToTest)));
        System.out.println(Arrays.deepToString(setZeroRowsAndColumns(matrixToTest)));
    }

    /*
        1.6 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate
        the image by 90 degrees. Can you do this in place?
     */
    public static int[][] rotateImageMatrix(int[][] matrix) {
        int N = matrix.length;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N - i; j++) {
                swap(matrix, i, j, N - 1 - j, N - 1 - i);
            }
        }
        for (int i = 0; i < N / 2; i++) {
            for (int j = 0; j < N; j++) {
                swap(matrix, i, j, N - 1 - i, j);
            }
        }
        return matrix;
    }

    private static void swap(int[][] matrix, int i, int j, int i1, int j1) {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[i1][j1];
        matrix[i1][j1] = temp;
    }

    /*
        1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
     */
    public static int[][] setZeroRowsAndColumns(int[][] matrix) {
        boolean[] zerosInRows = new boolean[matrix.length];
        boolean[] zerosInColumns = new boolean[matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0) {
                    zerosInRows[i] = true;
                    zerosInColumns[j] = true;
                }
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (zerosInColumns[j] || zerosInRows[i]) matrix[i][j] = 0;
            }
        }
        return matrix;
    }
}